import type {
  LoadingConfig,
  AdaptiveConfig,
  PaginationProps
} from "@pureadmin/table";
import { ref, onMounted, reactive, computed } from "vue";
import dayjs from "dayjs";
import {
  getFlowerPagination,
  getFlowerTypeOptions,
  updateFlowerStatus
} from "@/api/flower";
import type { Flower, FlowerTypeOptionItem } from "types/flower";
import {
  FlowerMaterial,
  FlowerOccasion,
  FlowerReceiver,
  FlowerStatus
} from "@/constants";
import { message } from "@/utils/message";

type OptionsMap = Record<number, { label: string; value: string }>;

export function useColumns(options: {
  onEdit?: (row: Flower, index: number) => void;
  onDelete?: (row: Flower, index: number) => void;
}) {
  const SERVER_URL = import.meta.env.VITE_SERVER_URL;
  const flowerTypeMap = ref<Record<number, FlowerTypeOptionItem>>({});
  const flowerReceiverMap: OptionsMap = FlowerReceiver.reduce((map, item) => {
    map[item.value] = item;
    return map;
  }, {});
  const flowerMaterialMap: OptionsMap = FlowerMaterial.reduce((map, item) => {
    map[item.value] = item;
    return map;
  }, {});
  const flowerOccasionMap: OptionsMap = FlowerOccasion.reduce((map, item) => {
    map[item.value] = item;
    return map;
  }, {});
  const flowerStatusMap: OptionsMap = FlowerStatus.reduce((map, item) => {
    map[item.value] = item;
    return map;
  }, {});

  const dataList = ref<Flower[]>([]);
  const loading = ref(true);
  // const searchText = ref<string | undefined>(undefined);
  const filter = reactive({
    presale: false,
    kw: undefined
  });
  const columns: TableColumnList = [
    // {
    //   label: "ID",
    //   prop: "id",
    //   fixed: "left"
    // },
    // {
    //   label: "创建日期",
    //   width: 160,
    //   prop: "created_on",
    //   cellRenderer: ({ row }) => (
    //     <>{dayjs(row.created_on).format("YYYY-MM-DD HH:mm:ss")}</>
    //   )
    // },
    {
      label: "名称",
      prop: "name",
      minWidth: 120,
      fixed: "left"
    },
    {
      label: "图片",
      prop: "images",
      width: 140,
      cellRenderer: ({ row }) => {
        if (row.images && row.images.length > 0) {
          return (
            <el-image
              style="width: 80px; height: 80px"
              src={SERVER_URL + row.images[0]}
              fit="cover"
              preview-src-list={row.images.map(item => SERVER_URL + item)}
              preview-teleported={true}
            />
          );
        }

        return;
      }
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        if (row.status === 1 && row.presale) {
          return <el-tag type="warning">预售</el-tag>;
        } else {
          return (
            <el-tag type={row.status === 1 ? "primary" : "info"}>
              {flowerStatusMap[row.status]
                ? flowerStatusMap[row.status].label
                : ""}
            </el-tag>
          );
        }
      }
    },
    {
      label: "预售时间",
      width: 190,
      prop: "presale",
      cellRenderer: ({ row }) => {
        if (row.presale) {
          return (
            <el-tag type="warning">
              {dayjs(row.presale_start_date).format("YYYY-MM-DD") +
                " ~ " +
                dayjs(row.presale_end_date).format("YYYY-MM-DD")}
            </el-tag>
          );
        }

        return;
      }
    },
    {
      label: "枝数",
      prop: "size",
      minWidth: 120
    },
    {
      label: "对象",
      prop: "receiver",
      minWidth: 120,
      cellRenderer: ({ row }) =>
        flowerReceiverMap[row.receiver]
          ? flowerReceiverMap[row.receiver].label
          : ""
    },
    {
      label: "花材",
      prop: "material",
      minWidth: 120,
      cellRenderer: ({ row }) =>
        flowerMaterialMap[row.material]
          ? flowerMaterialMap[row.material].label
          : ""
    },
    {
      label: "场合",
      prop: "occasion",
      minWidth: 120,
      cellRenderer: ({ row }) =>
        flowerOccasionMap[row.occasion]
          ? flowerOccasionMap[row.occasion].label
          : ""
    },
    {
      label: "分类",
      prop: "type",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        const map = computed(() => flowerTypeMap.value);
        return map.value[row.type] ? map.value[row.type].name : "";
      }
    },
    {
      label: "原价",
      prop: "original_price",
      minWidth: 120,
      cellRenderer: ({ row }) => "￥" + row.original_price
    },
    {
      label: "售价",
      prop: "price",
      minWidth: 120,
      cellRenderer: ({ row }) => "￥" + row.price
    },

    {
      label: "操作",
      width: 200,
      fixed: "right",
      cellRenderer: ({ index, row }) => (
        <>
          <el-button size="small" onClick={() => handleEdit(row, index)}>
            编辑
          </el-button>

          <el-popconfirm
            title={row.status === 1 ? "确认下架?" : "确认上架?"}
            placement="top-end"
            onConfirm={() => handleUpdateFlowerStatus(row)}
          >
            {{
              reference: () => (
                <el-button size="small" disabled={row.count > 0}>
                  {row.status === 1 ? "下架" : "上架"}
                </el-button>
              )
            }}
          </el-popconfirm>

          <el-popconfirm
            title="确认删除?"
            placement="top-end"
            onConfirm={() => handleDelete(row, index)}
          >
            {{
              reference: () => (
                <el-button size="small" type="danger" disabled={row.count > 0}>
                  删除
                </el-button>
              )
            }}
          </el-popconfirm>
        </>
      )
    }
  ];

  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 40, 60],
    total: 60,
    align: "right",
    background: true,
    size: "default"
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });

  /** 撑满内容区自适应高度相关配置 */
  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 110
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  interface RequestParams {
    page: number;
    page_size: number;
    kw?: string;
    presale?: boolean;
  }

  async function loadData(e: RequestParams) {
    try {
      loading.value = true;

      const params: RequestParams = {
        page: e.page,
        page_size: e.page_size
      };

      if (e.kw && e.kw.trim()) {
        params.kw = e.kw.trim();
      }

      if (filter.presale || params.presale) {
        params.presale = true;
      }

      const response = await getFlowerPagination({ ...params });

      pagination.total = response.total;
      dataList.value = response.data;
    } catch (e) {
      console.log(e);
    } finally {
      loading.value = false;
    }
  }

  async function onSizeChange() {
    pagination.currentPage = 1;

    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: filter.kw
    });
  }

  async function onCurrentChange() {
    loadingConfig.text = `正在加载第${pagination.currentPage}页...`;

    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: filter.kw
    });
  }

  async function handleEdit(row: Flower, index: number) {
    if (options.onEdit) {
      options.onEdit(row, index);
    }
  }

  async function handleDelete(row: Flower, index: number) {
    if (options.onDelete) {
      options.onDelete(row, index);
    }
  }

  async function handleUpdateFlowerStatus(row: Flower) {
    try {
      if (row.status === 1) {
        await updateFlowerStatus({ id: row.id, status: 2 });
      } else {
        await updateFlowerStatus({ id: row.id, status: 1 });
      }
      message("更新成功", { type: "success" });
      refresh();
    } catch (e) {
      if (e.response.data && e.response.data.message) {
        message(e.response.data.message, { type: "error" });
      } else {
        message("更新失败", { type: "error" });
      }
      console.log(e);
    }
  }

  onMounted(async () => {
    const response = await getFlowerTypeOptions();

    flowerTypeMap.value = response.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {});

    console.log(flowerTypeMap.value);

    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: filter.kw
    });
  });

  async function refresh() {
    await loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: filter.kw
    });
  }

  async function search() {
    pagination.currentPage = 1;
    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: filter.kw
    });
  }

  return {
    loading,
    columns,
    dataList,
    pagination,
    loadingConfig,
    adaptiveConfig,
    filter,
    onSizeChange,
    onCurrentChange,
    refresh,
    search
  };
}
